//
//  GXLinkView.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/12/13.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "GXLinkView.h"

@interface GXLinkView ()

@property (nonatomic, strong) NSMutableArray<UILabel *> *labelsM;
//二维数组，存放 ’上下两个（或三个）单位‘ 的label【inventoryManager专用】
@property (nonatomic, strong) NSMutableArray<NSMutableArray<UILabel *> *> *inventoryManagerLabels;

@property (nonatomic, strong) NSMutableArray<NSNumber *> *heightsM;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<NSNumber *> *> *inventoryManagerHeights;


@property (nonatomic, assign) BOOL isCreated;


@end

@implementation GXLinkView

+ (instancetype)linkViewWithControllerEnum:(ViewControllerEnum)controllerEnum {
    id obj = [[self alloc] init];
    ((GXLinkView *)obj).controllerEnum = controllerEnum;
    return obj;
}


#pragma mark - methods
- (BOOL)isTitlesEmpty {
    if (self.titles == nil || self.titles.count == 0) {
        return YES;
    }
    return NO;
}

- (BOOL)isLabelsEmpty {
    if (self.labelsM == nil || self.labelsM.count == 0) {
        return YES;
    }
    return NO;
}

- (void)setWidth:(CGFloat)width forIndex:(NSInteger)index {
    if ([self isTitlesEmpty] || index >= self.titles.count) {
        return;
    }
    
    //    NSLog(@"old: %@", @(_maxWidth).description);
    
    if (self.controllerEnum == ViewControllerDailyCash) {
        self.maxWidth -= self.labelsM[index].bounds.size.width;
        
        [self.labelsM[index] mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_offset(width);
        }];
        [self layoutIfNeeded];
        
        //计算总宽度
        self.maxWidth += self.labelsM[index].bounds.size.width;
        //    NSLog(@"new: %@", @(_maxWidth).description);
    }
    
    if (self.controllerEnum == ViewControllerInventoryManager) {
        self.maxWidth -= self.inventoryManagerLabels[index][0].bounds.size.width;
        //        NSLog(@"---001: %@", @(self.inventoryManagerLabels[index][0].bounds.size.width).description);
        [self.inventoryManagerLabels[index][0] mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_offset(width);
        }];
        [self layoutIfNeeded];
        //        NSLog(@"---002: %@", @(self.inventoryManagerLabels[index][0].bounds.size.width).description);
        self.maxWidth += width;
    }
    
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment forIndex:(NSInteger)index {
    if ([self isTitlesEmpty] || index >= self.titles.count) {
        return;
    }
    
    switch (self.controllerEnum) {
        case ViewControllerDailyCash:
            self.labelsM[index].textAlignment = textAlignment;
            break;
        case ViewControllerInventoryManager:
            for (UILabel *lbl in self.inventoryManagerLabels[index]) {
                lbl.textAlignment = textAlignment;
            }
            
        default:
            break;
    }
}

- (void)setFont:(UIFont *)font textColor:(UIColor *)textColor forIndex:(NSInteger)index {
    if ([self isTitlesEmpty] || index >= self.titles.count) {
        return;
    }
    self.labelsM[index].font = font;
    self.labelsM[index].textColor = textColor;
}


///distribute
- (void)distribute {
    for (int i = 0; i < self.labelsM.count; i++) {
        self.labelsM[i].text = self.titles[i];
    }
}


#pragma mark - setupUI
-(void) initUI {
    
    switch (self.controllerEnum) {
        case ViewControllerDailyCash:
            [self initUIWithEnumDailyCash];
            break;
        case ViewControllerInventoryManager:
            [self initUIWithEnumInventoryManager];
            break;
            
        default:
            break;
    }
    
    
    
}

- (void)initUIWithEnumInventoryManager {
    // 【箱,盒,瓶】
    self.maxHeight = 0;
    //
    if ([self isTitlesEmpty]) {
        return;
    }
    
    CGFloat elemWidth = 80;
    //二维数组，存放 ‘高度’
    NSMutableArray<NSMutableArray<NSNumber *> *> *heightsM = [NSMutableArray<NSMutableArray<NSNumber *> *> array];
    
    //二维数组，存放 ’上下两个（或三个）单位‘ 的label
    NSMutableArray<NSMutableArray<UILabel *> *> *labelsM = [NSMutableArray<NSMutableArray<UILabel *> *> array]; //
    //    NSLog(@"titles.count: %@", @(self.titles.count).description);
    for (int i = 0; i < self.titles.count; i ++) { //列
        
        NSArray *arr = [[NSString stringWithFormat:@"%@", self.titles[i]] componentsSeparatedByString:@","];
        //        NSLog(@"arr.count: %@", @(arr.count).description);
        //每列label高度的总和
        CGFloat colHeight = 0;
        //每列label的高度集合
        NSMutableArray<NSNumber *> *elemHeightsM = [NSMutableArray<NSNumber *> array];
        //每列label的集合
        NSMutableArray<UILabel *> *lblM = [NSMutableArray<UILabel *> arrayWithCapacity:3];
        
        //        NSLog(@"%@", @(arr.count).description);
        for (int j = 0; j < arr.count; j++) { //行
            
            UILabel *label = [[UILabel alloc] init];
            [self addSubview:label];
            
            if (self.isPrefix && i == 0) { //tvPrefix
                //
                UILabel *lblIndex = [[UILabel alloc] init];
                [self addSubview:lblIndex];
                
                lblIndex.font = [UIFont systemFontOfSize:12];
                lblIndex.textColor = [UIColor whiteColor];
                lblIndex.backgroundColor = [UIColor orangeColor];
                lblIndex.textAlignment = NSTextAlignmentCenter;
                lblIndex.text = arr[j];
                
                [lblIndex mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(label);
                    make.centerX.equalTo(label);
                    make.size.mas_offset(CGSizeMake(22, 20));
                }];
                
            } else {
                label.text = arr[j];
            }
            
            label.tag = j;
            label.font = [UIFont systemFontOfSize:12];
            label.numberOfLines = 0;
            label.textAlignment = NSTextAlignmentRight;
//            label.backgroundColor = [UIColor gx_randomColor];
            
            CGFloat height = 0;
            CGRect lblTextRect = [label.text boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]} context:nil];
            height = lblTextRect.size.height;
            //            NSLog(@"%@", @(height).description);
            height = 8 + (height <= 16 ? 16 : height);
            colHeight += height;
            [elemHeightsM addObject:@(height)];
            
            [lblM addObject:label];
        }//for arr.count  end
        
        [labelsM addObject:lblM];
        [heightsM addObject:elemHeightsM];
        
        self.inventoryManagerLabels = labelsM;
        self.inventoryManagerHeights = heightsM;
        _maxWidth += elemWidth;
        
        //        NSLog(@"_maxHeight: %.2f, colHeight: %.2f", _maxHeight, colHeight);
        _maxHeight = MAX(_maxHeight, colHeight);
        
    }//for _titles.cout  end
    
    //    _maxWidth += 10;
    
    //layout   NSMutableArray<NSMutableArray<UILabel *> *> *labelsM
    //first colum
    [labelsM[0][0] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.equalTo(self).mas_offset(3);
        make.width.mas_offset(elemWidth);
        make.height.mas_offset([heightsM[0][0] floatValue]);
    }];
    
    for (int i = 1; i < labelsM[0].count; i ++) {
        [labelsM[0][i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(labelsM[0][i-1].mas_bottom).mas_offset(1);
            make.leading.equalTo(labelsM[0][0]).mas_offset(0);
            make.width.equalTo(labelsM[0][0]);
            make.height.mas_offset([heightsM[0][i] floatValue]);
        }];
    }
    
    //other colums
    if (labelsM.count < 2) {
        return;
    }
    for (int i = 1; i < labelsM.count; i++) {
        
        [labelsM[i][0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(labelsM[i-1][0]).mas_offset(0);
            make.leading.equalTo(labelsM[i-1][0].mas_trailing).mas_offset(0);
            make.width.mas_offset(elemWidth);
            if (!self.isPrefix) {
                make.height.mas_offset([heightsM[i][0] floatValue]);
            }
        }];
        for (int j = 1; j < labelsM[i].count; j++) {
            
            [labelsM[i][j] mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(labelsM[i][j-1].mas_bottom).mas_offset(1);
                make.leading.equalTo(labelsM[i][j-1]).mas_offset(0);
                make.width.equalTo(labelsM[i][j-1]);
                make.height.mas_offset([heightsM[i][j] floatValue]);
            }];
        }
    }
    
    [self layoutIfNeeded];
    self.isCreated = YES;
}

- (void)initUIWithEnumDailyCash {
    
    self.maxHeight = 0;
    //
    if ([self isTitlesEmpty]) {
        return;
    }
    
    CGFloat elemWidth = 80;
    NSMutableArray<NSNumber *> *heightsM = [NSMutableArray<NSNumber *> array];
    
    NSMutableArray<UILabel *> *labelsM = [NSMutableArray<UILabel *> array];
    for (int i = 0; i < _titles.count; i++) {
        UILabel *label = [[UILabel alloc] init];
        [self addSubview:label];
        
        //        label.backgroundColor = [UIColor gx_randomColor];
        label.text = self.titles[i];
        label.font = [UIFont systemFontOfSize:12];
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        
        CGFloat height = 0;
        //        CGFloat width = 0;
        CGRect rect = [label.text boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
        
        height = rect.size.height;
        //        NSLog(@"height: %@, _height: %@", @(height).description, @(_height).description);
        
        [heightsM addObject:@(height)];
        
        _maxWidth += elemWidth;
        _maxHeight = MAX(_maxHeight, height);
        //        NSLog(@"_height: %@", @(_height).description);
        
        [labelsM addObject:label];
    }
    self.labelsM = labelsM;
    self.heightsM = heightsM;
    
    //layout
    [self.labelsM[0] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.equalTo(self).mas_offset(3);
        make.width.mas_offset(elemWidth);
        make.height.mas_offset([_heightsM[0] floatValue] + 8);
    }];
    
    if (self.titles.count >= 2) {
        //
        for (int i = 1; i < self.labelsM.count - 1; i++) {
            [self.labelsM[i] mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.labelsM[0]).mas_offset(0);
                make.leading.equalTo(self.labelsM[i-1].mas_trailing).mas_offset(0);
                make.width.mas_offset(elemWidth);
                make.height.mas_offset([self.heightsM[i] floatValue] + 8);
            }];
        }//for end
        
        [self.labelsM.lastObject mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.labelsM[0]).mas_offset(0);
            make.leading.equalTo(self.labelsM[self.labelsM.count - 2].mas_trailing);
            make.trailing.equalTo(self).mas_offset(0);
            make.width.mas_offset(elemWidth);
            make.height.mas_offset([self.heightsM.lastObject floatValue] + 8);
        }];
        
    } //count >= 2  end
    [self layoutIfNeeded];
    self.isCreated = YES;
}



#pragma mark - setter & getter
- (void)setTitles:(NSArray<NSString *> *)titles {
    if (self.controllerEnum == ViewControllerNone) {
        return;
    }
    // 【箱,瓶】
    _titles = titles;
    
    if (!self.isCreated) {
        [self initUI];
    } else {
        [self distribute];
    }
}

- (void)setFirstColor:(UIColor *)firstColor {
    if (self.controllerEnum == ViewControllerNone) {
        return;
    }
    _firstColor = firstColor;
    
    self.labelsM[0].textColor = firstColor;
}

- (void)setBgColor:(UIColor *)bgColor {
    if (self.controllerEnum == ViewControllerNone) {
        return;
    }
    _bgColor = bgColor;
    
    self.backgroundColor = bgColor;
    for (int i = 0; i < self.labelsM.count; i++) {
        self.labelsM[i].backgroundColor = bgColor;
    }
}

- (void)setColWidthArr:(NSArray<NSNumber *> *)colWidthArr {
    if (self.controllerEnum == ViewControllerNone) {
        return;
    }
    _colWidthArr = colWidthArr;
    
    if (colWidthArr.count <= self.labelsM.count) {
        for (int i = 0; i < colWidthArr.count; i++) {
            [self setWidth:[colWidthArr[i] floatValue] forIndex:i];
        }
    }
}




@end
